import { cn } from "@renderer/lib/utils";
import type { CSSProperties, ReactNode } from "react";
import { useEffect, useMemo, useRef, useState } from "react";

export type SegmentedOption = {
  key: string;
  icon?: ReactNode;
  label: ReactNode;
};

interface SegmentedButtonsProps {
  options: SegmentedOption[];
  selectedKey?: string | null;
  onSelect: (key: string) => void;
}

export function SegmentedButtons(props: SegmentedButtonsProps) {
  const { options, selectedKey, onSelect } = props;

  const [thumbStyle, setThumbStyle] = useState<CSSProperties>({});
  const itemsRef = useRef<(HTMLButtonElement | null)[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);

  const selectedIndex = useMemo(
    () => options.findIndex((o) => o.key === selectedKey),
    [options, selectedKey],
  );

  const setItemRef = (index: number) => (el: HTMLButtonElement | null) => {
    itemsRef.current[index] = el;
  };

  useEffect(() => {
    if (selectedIndex === -1) return;
    const item = itemsRef.current[selectedIndex];
    const container = containerRef.current;
    if (!item || !container) return;

    const containerRect = container.getBoundingClientRect();
    const itemRect = item.getBoundingClientRect();

    setThumbStyle({
      left: `${itemRect.left - containerRect.left}px`,
      width: `${itemRect.width}px`,
    });
  }, [selectedIndex]);

  return (
    <div
      ref={containerRef}
      className="relative flex h-11 items-center rounded-[10px] bg-setting px-2"
    >
      {Object.hasOwn(thumbStyle, "left") && (
        <div
          className="absolute z-1 h-[32px] rounded-md bg-accent transition-all duration-400 ease-in-out"
          style={thumbStyle}
        />
      )}

      <div className="flex w-full gap-2">
        {options.map((option, index) => {
          const isActive = selectedKey === option.key;
          return (
            <button
              key={option.key}
              ref={setItemRef(index)}
              className={cn(
                "relative z-2 flex h-[32px] flex-1 cursor-pointer items-center justify-center gap-1 rounded-md text-sm",
                isActive
                  ? "text-accent-fg"
                  : "z-1 text-secondary-fg hover:bg-hover-primary",
              )}
              type="button"
              onMouseDown={() => onSelect(option.key)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  onSelect(option.key);
                }
              }}
              aria-pressed={isActive}
            >
              {option.icon}
              <span>{option.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

export default SegmentedButtons;
